#!/usr/bin/env python
# -*- coding= utf-8 -*-

"""Class to handle a local PySlip tileset."""


import os
import cPickle as pickle
import tkinter_error
try:
    import wx
except ImportError:
    msg = 'Sorry, you must install wxPython'
    tkinter_error.tkinter_error(msg)

# If we have log.py, well and good.  Otherwise ...
try:
    import log
    log = log.Log('pyslip.log', log.Log.DEBUG)
except ImportError:
    def log(*args, **kwargs):
        pass

import pyslip
from tiles import Tiles


###############################################################################
# Make a Tile object for local tiles
###############################################################################

class LocalTiles(Tiles):
    """Override the Tiles base class."""

    TileSize = 256      # width/height of tiles

    # name of the INFO file in subdirectories of the tile cache directory
    TileInfoFilename = 'tile.info'

    def __init__(self, tile_dir, levels=None):
        """Override the base class for local tiles.

        tile_dir  directory for existing cached tiles
        levels    list of level numbers that will be used
        """

        Tiles.__init__(self, tile_dir, levels)

        # open top-level info file
        info_file = os.path.join(tile_dir, self.TileInfoFilename)
        try:
            fd = open(info_file, 'rb')
            (self.extent, self.tile_size,
                 self.sea_colour, self.land_colour) = pickle.load(fd)
            fd.close()
        except IOError:
            msg = "'%s' doesn't appear to be a local tile directory" % tile_dir
            raise Exception(msg)

        self.tile_size_x = self.TileSize
        self.tile_size_y = self.TileSize

    def GetInfo(self, level):
        """Get tile info for a particular level.

        level  the level to get tile info for

        Returns (num_tiles_x, num_tiles_y, ppd_x, ppd_y).
        """

        # see if we can open the tile info file.
        info_file = os.path.join(self.tile_cache_dir, '%d' % level,
                                 self.TileInfoFilename)
        try:
            fd = open(info_file, 'rb')
        except IOError:
            return None

        # OK, looks like we actually do have this level!
        info = pickle.load(fd)
        fd.close()

        return info

    def ConvertGeo2View(self, lonlat, view_offset_x, view_offset_y, view_llon,
                        view_tlat, ppd_x, ppd_y):
        """Convert a geo (lon+lat) position to view pixel coords.

        lonlat  (longitude, latitude) of point

        Return screen pixels coordinates of the point (x,y).
        """

        (lon, lat) = lonlat

        return ((lon - view_llon) * ppd_x,
                (view_tlat - lat) * ppd_y)

    def ConvertView2Geo(self, xy, view_offset_x, view_offset_y, map_llon,
                        map_tlat, ppd_x, ppd_y):
        """Convert an x,y view position to geo lon+lat.

        xy  tuple of view X & Y coordinate (pixels)

        Return a tuple (lon, lat) - geo coordinates of the point.
        """

        (x, y) = xy

        # x_pix is from left map edge, y_pix from top map edge
        x_pix = x + view_offset_x
        y_pix = y + view_offset_y

        lon = map_llon + x_pix/ppd_x
        lat = map_tlat - y_pix/ppd_y

        return (lon, lat)
